package com.coffee.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.utils.AESUtil;
import com.coffee.core.util.DateUtil;
import com.coffee.order.api.sku.service.SkuOrderService;
import com.coffee.order.api.utils.MessageUtil;
import com.coffee.order.api.utils.PayStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping()
public class NotifyController {

    @Value("${parameter.weixin.signKey}")
    private String signKey;

    @DubboReference(check = false)
    private SkuOrderService skuOrderService;

    @RequestMapping("/weixin/refund/notify")
    public void callBack(HttpServletRequest request, HttpServletResponse response) {

        log.info("微信支付成功,微信发送的callback信息,可以开始修改订单信息");
        try {
            PrintWriter out = response.getWriter();
            Map<String, String> notifyMap = MessageUtil.parseXml(request);
            log.info("微信支付成功,notifyMap==" + JSONObject.toJSONString(notifyMap));
            //支付成功进入
            if (notifyMap.get("return_code").equals("SUCCESS")) {
                //2.1解密参数，业务处理
                String req_info = notifyMap.get("req_info");
                String resultXml = AESUtil.decryptData(req_info, signKey);
                Map<String, String> reqInfoMap = MessageUtil.parseXml(resultXml);
                // 商户订单号
                String ordersSn = reqInfoMap.get("out_refund_no");
                // 实际支付的订单金额:单位 分
                String amountpaid = reqInfoMap.get("total_fee");

                String refundId = reqInfoMap.get("refund_id");

                String successTime = reqInfoMap.get("success_time");
                // 将分转换成元-实际支付金额:元
                BigDecimal amountPay = (new BigDecimal(amountpaid).divide(new BigDecimal("100"))).setScale(2);
                Integer payOrderId = Integer.parseInt(ordersSn.split("-")[1]);
                //下面做业务处理
                log.info("===notify===reqInfoMap==" + JSONObject.toJSONString(reqInfoMap));
                //比如修改下单时间、订单状态等等...
                skuOrderService.applyRefundNotify(payOrderId, DateUtil.getDateTime(successTime, DateUtil.DEFAULT_DATETIME_FORMAT), refundId);
                PayStatus payStatus = new PayStatus();
                payStatus.setReturnCode("SUCCESS");
                payStatus.setReturnMsg("OK");
                String xml = MessageUtil.payStatusToXml(payStatus);
                out.print(xml);
                out.flush();
                out.close();
                return;
            }
        } catch (Exception e) {
            log.error("-----------微信回调错误,解析xml出错:", e);
            e.printStackTrace();
            return;
        }
    }
}
